// 在当前文件夹创建或者更新messages.js
const path = require('path');
const fs = require('fs');
const prettier = require('prettier');
const traverse2 = require('@babel/traverse');
const parser = require('@babel/parser');
const t = require('@babel/types');
const generator = require('@babel/generator').default;
//  import chalk from 'chalk';

const traverse = traverse2.default;
// const parser = parse2.default
async function createMessage(data) {
  const { dir, full_map } = data;
  console.log(path.resolve(dir, 'messages.js'));
  const messagePath = path.resolve(dir, 'messages.js');
  if (fs.existsSync(messagePath)) {
    // 如果存在messages.js 进行更新
    var code = fs.readFileSync(messagePath, 'utf8');
    const [added, removed, ast] = traverseMessage({ code, full_map });

    const generatorCode = generator(ast, {
      retainLines: true,
      jsescOption: {
        minimal: true,
      },
    }).code;
    const newCode = prettier.format(generatorCode, {
      parser: 'typescript',
    });

    // console.log(chalk.green(`新增${added}`));
    fs.writeFileSync(messagePath, await newCode, 'utf-8');
  } else {
    // 如果不存在，新增

    // 创建所有描述的obj
    const tObj = {};
    full_map.forEach((value, item) => {
      tObj[item] = {
        id: item,
        defaultMessage: value,
      };
    });
    console.log('tobj', tObj);

    // 创建依赖导入str
    const importStr = `import { defineMessages } from 'react-intl';`;

    const contentStr = 'export default defineMessages(' + JSON.stringify(tObj) + ');';

    const initData = importStr + contentStr;
    const code = prettier.format(initData, {
      parser: 'typescript',
    });

    fs.writeFileSync(messagePath, await code, 'utf-8');
  }
}

function traverseMessage(data) {
  const { code, full_map } = data;

  let modified = false;
  let added = 0;
  let removed = 0;
  var ast = parser.parse(code, {
    sourceType: 'module',
    plugins: ['typescript', 'jsx'],
  });
  traverse(ast, {
    enter(path) {
      // console.log(path)
    },
    /*   ObjectExpression(path){
          console.log(path)
        }, */
    Program(path) {
      path.traverse({
        ObjectExpression(path1) {
          const { node } = path1;
          if (node.properties.length) {
            if (node.properties[0].key.name == 'id' && t.isIdentifier(node.properties[0].key)) {
              // 只处理对应的obj
              const mValue = node.properties[1].value.value;
              const mKey = node.properties[0].value.value;
              // full_map 中是否存在 mkey
              // todo
              // 不存在mkey
              if (!full_map.has(mKey)) {
                delete node.properties;
                removed++;
                console.log('删除');
              }
            }
          }
        },
      });
    },
    CallExpression(path) {
      // const { node } = path1;
       // 检查是否是 defineMessages 调用
       if (
        t.isIdentifier(path.node.callee, { name: 'defineMessages' }) &&
        path.node.arguments.length === 1 &&
        t.isObjectExpression(path.node.arguments[0])
      ){
        const node = path.node.arguments[0];
        node.properties = node.properties.filter((item) => {
          return item.value.properties;
        });
          // 只处理对应的obj
          const KSet = new Set(node.properties.map((item) => item.key.value || item.key.name));

          full_map.forEach((value, key) => {
            if (!KSet.has(key)) {
              added++;
              console.log('新增');
              const asrcodeObjectExpression = t.objectExpression([
                // 创建 'id' 属性
                t.objectProperty(t.identifier('id'), t.stringLiteral(key)),
                // 创建 'value' 属性
                t.objectProperty(t.identifier('value'), t.stringLiteral(value))
              ]);
              const propertyC = t.objectProperty(t.identifier(key),asrcodeObjectExpression);
              node.properties.push(propertyC);
            }
          });
      }
    },
  });

  return [added, removed, ast];
}

module.exports = {
  createMessage,
};
